package 晚间作业0316.Doc12_课后习题;

import java.util.Random;

/**
 * 2.【难】给定一个长度，生成一个指定长度的字符串，这个字符串由随机的字母、数字或下划线组成。(不用必
 * 须同时包含字母、数字、下划线)
 * randomString(5) -> hi2Pd
 */
public class Doc12_02 {

    public static void main(String[] args) {
        System.out.println(randomString(5));
    }

    private static String randomString(int length) {
        StringBuilder stringBuffer = new StringBuilder();
        int randomIndex;
        char[] randomChar={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
                'A','B','C','D','E','F','G','H','I','J','K','L', 'M','N','0','P','Q','R','S','T','U','V','W','X','Y','Z',
                '0','1','2','3','4','5','6','7','8','9','_'
        };
        for(int i = 0; i < length; i++) {
            randomIndex = new Random().nextInt(randomChar.length);
            stringBuffer.append(randomChar[randomIndex]);
        }
        return stringBuffer.toString();
    }
}
